<?php

namespace plugin\tuCrontabs\app\common;

use plugin\tuCrontabs\app\model\CrontabLogModel;
use support\Db;

class Test
{

    /**
     * 定时清理日志
     * \plugin\tuCrontabs\app\common\Test::clearLog(7);
     * @param $dayNumber  清理N天前的日志
     * @return void
     */
    static function clearLog($dayNumber = 7){
        $rootPart = base_path().'/runtime/logs/';
        $logtypes = ['debug','err','sql','webman'];// 需要清理的日志类型
        $timer = strtotime(date('Y-m-d')) - $dayNumber * 86400;
        $number = 0;
        foreach ($logtypes as $logtype){
            $dir = $rootPart.$logtype;
            if(!is_dir($dir)) continue;
            $files = scandir($dir);
            foreach ($files as $file){
                if($file!='.' && $file!='..'){
                    $date = getSubstr($file,$logtype.'-','.log');
                    if($date && strtotime($date)<$timer){
                        // 满足条件 删除记录
                        unlink($dir."/{$file}");
                        $number++;
                    }
                }
            }
        }
        return "本次清理{$number}个日志文件";
    }

    /**
     * 定时清理 定时任务产生的日志记录
     * \plugin\tuCrontabs\app\common\Test::clearCrontabLog(3);
     * @param $dayNumber
     * @return void
     */
    static function clearCrontabLog($dayNumber = 3){
        $time = time() - $dayNumber*86400;
        $number = CrontabLogModel::where([['create_time','<',$time]])->delete();
        return "成功清理{$number}条日志";
    }

    /**
     * 定时清理 Redis队列创建的数据库表
     * @param $dayNumber
     * @return string
     */
    static function clearGlobalLog($dayNumber = 3){
        // 获取N天前的时间戳
        $timer = strtotime(date('Y-m-d')) - $dayNumber * 86400;
        $tableLog = ['global_log_','http_log_'];
        $tables = json_decode(json_encode(Db::select("SHOW TABLES")),1);
        $key = array_keys($tables[0])[0];
        $number = 0;
        foreach ($tables as $k=>$table){
            $tableName = $table[$key];
            // 判断表名是否是日志表
            foreach ($tableLog as $tabLog){
                if(strpos($tableName,$tabLog)!==false ){
                    $time = str_replace($tabLog,'',$tableName);
                    if($time){
                        $tableTime = strtotime($time);
                        if($tableTime<$timer){
                            // 删除表
                            Db::statement("DROP TABLE {$tableName};");
                            $number++;
                        }
                    }
                    break;
                }
            }
        }
        return "成功清理{$number}条日志";
    }

    static function demo(){
        return 'demo1 调用案例';
    }

    static function demo2(){
        sleep(10);
        return 'demo2 延迟10秒后调用';
    }


}